package com.comp3111.happymeal;


import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.configuration.Configuration;
import com.controller.*;
import com.object.*;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

public class DiscoverPageActivity extends NavigationDrawerActivity {
	
	//Back button
	private int backButtonCount;
	
	ImageView iv;
	private ListView mealListView;
    private SimpleAdapter adapter;
    private List<Integer> mealIdList;
    // Store the mealId into a list to allow getting the mealId of meal in mealListView of certain position
    
    //for creating picture
    Drawable drawableTmp;
    String drawableURL;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_using_listview_only); 
        createDrawer();
        
        //Initialize the back button count
        backButtonCount = 0;
        
        mealListView = (ListView) findViewById(R.id.page_using_listview_only_listview);
        adapter = new SimpleAdapter(this, getDataDiscoverPageListview(), R.layout.food_list,
				new String[]{"food_pic","food_name","restaurant_name", "love", "price"},
				new int[]{R.id.food_list_picture, R.id.food_name, R.id.restaurant_name, R.id.love, R.id.price});
        mealListView.setAdapter(adapter);
        
        adapter.setViewBinder(new ViewBinder(){
        	public boolean setViewValue(View view,Object data,String textRepresentation){
				if(view instanceof ImageView && data instanceof Drawable){
					ImageView iv=(ImageView)view;
					iv.setImageDrawable((Drawable)data);
					return true;
				}
				else return false;
			}
        });
        
        mealListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            	int mealId = mealIdList.get(position);
                //Toast.makeText(DiscoverPageActivity.this,"ID�G" + Integer.toString(mealId) ,Toast.LENGTH_SHORT).show();
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(DiscoverPageActivity.this, FoodPageActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("MEALID",Integer.toString(mealId).trim());
					
				//Go to next page
				startActivity(intentPass);

            }
        });
    
        //Release unused ram
        System.gc();
    }
    
    private List<Map<String, Object>> getDataDiscoverPageListview() {
    	
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		mealIdList = new ArrayList<Integer>();
		
		MealFetch mealFetch = new MealFetch();
		RestaurantFetch restaurantFetch = new RestaurantFetch();
	    List<Meal> mealList = mealFetch.fetchAllMeal();
	    
	    //List<Restaurant> restaurantList = restaurantFetch.fetchAllRestaurant();
	    
	    if(mealList != null){
		    for(Meal meal : mealList){
				Map<String, Object> map = new HashMap<String, Object>();
				
				drawableURL = Configuration.baseURL + meal.getPicture();

				
				//Start a new thread and use POST method to send telephone and passcode to authURL
		        //Start a new thread to attempt Login (requirement when connecting online)
				Thread attemptThread = new Thread(new Runnable(){  
					public void run(){  
						drawableTmp = loadImageFromURL(drawableURL);
						
					}
				});  
				attemptThread.start();
				
				while(attemptThread.isAlive()){
					//Wait for server response
				}
				
				map.put("food_pic", drawableTmp);
				map.put("food_name", meal.getName());
				int id = meal.getRestaurant();
				map.put("restaurant_name", restaurantFetch.fetchRestaurantNameById(id));
				map.put("love", Integer.toString(mealFetch.fetchMealLikeById(meal.getId())) + " loves");
				map.put("price", "$" + meal.getPrice());
				
				list.add(map);
				mealIdList.add(meal.getId());
	    	}
	    }
	    
		return list;
	}
    
    //the app will not allow it to go back to previous Activity through back
  	// Override the back button to quit the app if back is pressed twice
    public void onBackPressed(){
		if(Configuration.showLog){
			Log.d("DiscoverPageActivity", "onBackPressed");
		}
			
        if(backButtonCount >= 1){
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }else{
            Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
            backButtonCount++;
        }
	}
    
    private Drawable loadImageFromURL(String url){
        try{
        	InputStream is = (InputStream) new URL(url).getContent();
            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
            return new BitmapDrawable(getResources(), tmp);
            //Drawable draw = Drawable.createFromStream(is, "src");
            //return draw;
        }catch (Exception e) {
            //TODO handle error
            Log.i("loadingImg", e.toString());
            return null;
        }
    }

}



/*public class DiscoverPageActivity extends NavigationDrawerActivity {
	
	//Drawer
	private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;

	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discover_page);

        //Initialize the backButtonCount
        backButtonCount = 0;
        
        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.navigationMenuItem);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        
        
        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        
        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  //host Activity
                mDrawerLayout,        // DrawerLayout object 
                R.drawable.ic_drawer,  //nav drawer image to replace 'Up' caret 
                R.string.drawer_open, //"open drawer" description for accessibility 
                R.string.drawer_close   //"close drawer" description for accessibility 
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
        
        
         //Example on how to use Fetch Classes
         
        UserFetch userFetch = new UserFetch();
        User user = userFetch.fetchUserById(33);
        User user3 = userFetch.fetchUserById(35);
        
        Log.d("DiscoverPageActivity",user.getName());
        Log.d("DiscoverPageActivity",user.getDescription());
        Log.d("DiscoverPageActivity",user.getProfilePicture());

        Log.d("DiscoverPageActivity",user3.getName());
        Log.d("DiscoverPageActivity",user3.getDescription());
        Log.d("DiscoverPageActivity",user3.getProfilePicture());
        
        Log.d("DiscoverPageActivity","===============RESTAURANT==============");
        
        //Example on how to use RestaurantFetch Class
        RestaurantFetch restaurantFetch = new RestaurantFetch();
        Restaurant restaurant = restaurantFetch.fetchRestaurantById(8);
        Log.d("DiscoverPageActivity",restaurant.getName());
        Log.d("DiscoverPageActivity",restaurant.getAddress());
        Log.d("DiscoverPageActivity",restaurant.getTelephone());
        Log.d("DiscoverPageActivity",restaurant.getOpenHours());
        Log.d("DiscoverPageActivity",restaurant.getDescription());
        Log.d("DiscoverPageActivity",restaurant.getProfilePicture());
        for(int i=0;i<Configuration.tagNumber;i++){
        	Log.d("DiscoverPageActivity",restaurant.getTagByIndex(i));
        }
        Log.d("DiscoverPageActivity",restaurant.getCoupon());
        
        Log.d("DiscoverPageActivity","===========================================");
        
        RestaurantFetch restaurantFetch2 = new RestaurantFetch();
        List<Restaurant> restaurantList = restaurantFetch2.fetchAllRestaurant();
        for(Restaurant eachRestaurant: restaurantList){
        	Log.d("DiscoverPageActivity","==============EACH RESTAURANT==============");
        	Log.d("DiscoverPageActivity","Restaurant ID  : " + Integer.toString(eachRestaurant.getId()));
        	Log.d("DiscoverPageActivity","Restaurant Name:" + eachRestaurant.getName());
            Log.d("DiscoverPageActivity","Restaurant Addr:" + eachRestaurant.getAddress());
            Log.d("DiscoverPageActivity","Restaurant Tele:" + eachRestaurant.getTelephone());
            Log.d("DiscoverPageActivity","Restaurant Open:" + eachRestaurant.getOpenHours());
            Log.d("DiscoverPageActivity","Restaurant Desc:" + eachRestaurant.getDescription());
            Log.d("DiscoverPageActivity","Restaurant ProP:" + eachRestaurant.getProfilePicture());
            for(int i=0;i<Configuration.tagNumber;i++){
            	Log.d("DiscoverPageActivity","Restaurant Tag :" + Integer.toString(i) + " - "+ eachRestaurant.getTagByIndex(i));
            }
            Log.d("DiscoverPageActivity","Restaurant Coup:" + eachRestaurant.getCoupon());
        }
        
        Log.d("DiscoverPageActivity","===========================================");
        
        Log.d("DiscoverPageActivity","====================MEAL===================");
        
        MealFetch mealFetch = new MealFetch();
        Meal meal = mealFetch.fetchMealById(3);
        Log.d("DiscoverPageActivity",meal.getName());
        Log.d("DiscoverPageActivity",Integer.toString(meal.getRestaurant()));
        Log.d("DiscoverPageActivity",meal.getDescription());
        Log.d("DiscoverPageActivity",meal.getPicture());
        for(int i=0;i<Configuration.tagNumber;i++){
        	Log.d("DiscoverPageActivity",meal.getTagByIndex(i));
        }
        Log.d("DiscoverPageActivity",meal.getPrice());
        Log.d("DiscoverPageActivity","Like = " + Integer.toString(mealFetch.fetchMealLikeById(meal.getId())));
        
        Log.d("DiscoverPageActivity","===========================================");
        
        Log.d("DiscoverPageActivity","==============Restaurant Comment==============");
        
        RestaurantCommentFetch restaurantCommentFetch = new RestaurantCommentFetch();
        RestaurantComment restaurantComment = restaurantCommentFetch.fetchRestaurantCommentById(4);
        Log.d("DiscoverPageActivity",userFetch.fetchUserNameById(restaurantComment.getUser()));
        Log.d("DiscoverPageActivity",restaurantFetch.fetchRestaurantNameById(restaurantComment.getRestaurant()));
        Log.d("DiscoverPageActivity",Integer.toString(restaurantComment.getRating()));
        Log.d("DiscoverPageActivity",restaurantComment.getComment());
        Log.d("DiscoverPageActivity",restaurantComment.getCreateDate());
        
        List<RestaurantComment> restaurantCommentList = restaurantCommentFetch.fetchAllRestaurantComment();
        for(RestaurantComment eachRestaurantComment : restaurantCommentList){
        	Log.d("DiscoverPageActivity","==============EACH RESTAURANT COMMENT==============");
        	Log.d("DiscoverPageActivity",userFetch.fetchUserNameById(eachRestaurantComment.getUser()));
            Log.d("DiscoverPageActivity",restaurantFetch.fetchRestaurantNameById(eachRestaurantComment.getRestaurant()));
            Log.d("DiscoverPageActivity",Integer.toString(eachRestaurantComment.getRating()));
            Log.d("DiscoverPageActivity",eachRestaurantComment.getComment());
            Log.d("DiscoverPageActivity",eachRestaurantComment.getCreateDate());
        }
        
        Log.d("DiscoverPageActivity","===========================================");
        
        Log.d("DiscoverPageActivity","============== Meal Comment ==============");
        
        MealCommentFetch mealCommentFetch = new MealCommentFetch();
        MealComment mealComment = mealCommentFetch.fetchMealCommentById(4);
        Log.d("DiscoverPageActivity",userFetch.fetchUserNameById(mealComment.getUser()));
        Log.d("DiscoverPageActivity",mealFetch.fetchMealNameById(mealComment.getMeal()));
        Log.d("DiscoverPageActivity",mealComment.getComment());
        Log.d("DiscoverPageActivity",mealComment.getCreateDate());
        
        List<MealComment> mealCommentList = mealCommentFetch.fetchAllMealComment();
        for(MealComment eachMealComment : mealCommentList){
        	Log.d("DiscoverPageActivity","==============EACH RESTAURANT COMMENT==============");
        	Log.d("DiscoverPageActivity",userFetch.fetchUserNameById(eachMealComment.getUser()));
            Log.d("DiscoverPageActivity",mealFetch.fetchMealNameById(eachMealComment.getMeal()));
            Log.d("DiscoverPageActivity",eachMealComment.getComment());
            Log.d("DiscoverPageActivity",eachMealComment.getCreateDate());
            
        }
        
        Log.d("DiscoverPageActivity","===========================================");
        
        
        Log.d("DiscoverPageActivity","IMEI = " + Owner.imei);
        
        
          //Example END
         
        
    }
    
    
    
	  

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //Called whenever we call invalidateOptionsMenu()
    @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        switch(item.getItemId()) {
        case R.id.action_websearch:
            // create intent to perform web search for this planet
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
            // catch event that there's no activity to handle intent
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	
	//The click listner for ListView in the navigation drawer 
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
    	
    	Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);
        
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
		
        
        // Handle Navigation Options
        Intent intent;
        switch (position) {
            case 0:
                //Do nothing
                break;
            case 1:
            	//intent = new Intent(DiscoverPageActivity.this, SearchActivity.class);
            	//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                //startActivity(intent);
                break;
        }
            
            
        
        
        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }
    
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.navigationMenuItem)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            //((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }
}
*/